import GridCellEditWrapper from '@/components/form/gridcelleditwrapper';
import { BaseSelect } from '@/components/form/loupeselect';
import { getRoleField, getRoleInfo } from '@/utils/role';
import { isEmpty } from 'lodash';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import { renderlinkEle } from '../utils';
import SelectorModal from './SelectorModal';

const SelectorFormItem = (props: any) => {
  const {
    value,
    valueProp,
    labelProp,
    multiple,
    onChange,
    dispatch,
    withAuth,
    userId,
    listRoles,
    listRolesByAuth,
    listRolesFilters,
    showMode,
    linkTo,
    customShow,
    onBlur,
    ...restProps
  } = props;

  const [visible, setVisible] = useState(false);
  const [selectFocus, setSelectFocus] = useState(false);

  const fetch = useCallback(() => {
    if ((withAuth && listRolesByAuth.length) || (!withAuth && listRoles.length)) return;
    dispatch({ type: 'selectors/fetchAllRole', payload: { withAuth } });
  }, [withAuth, listRoles, listRolesByAuth]);

  //弹窗onOK事件
  const handlerChange = useCallback((selectedRowKeys: string[]) => {
    const ret: any = multiple ? selectedRowKeys : selectedRowKeys[0];
    onChange && onChange(!multiple ? ret : ret.length ? ret : null);
    setVisible(false);
  }, []);

  //select下拉框搜索
  const handlerSelectorSearch = useCallback(
    (keywords: any) => {
      if (keywords) {
        dispatch({ type: 'selectors/fetchAllRole', payload: { withAuth, keywords } });
      } else {
        dispatch({ type: 'selectors/save', payload: { listRolesFilters: null } });
      }
    },
    [withAuth],
  );

  //select下拉框选择
  const handlerSelectorChange = useCallback((ret: any) => {
    onChange && onChange(ret);
  }, []);

  const handlerSelectorBlur = useCallback(() => {
    setSelectFocus(false);
    dispatch({ type: 'selectors/save', payload: { listRolesFilters: null } });
  }, [dispatch]);

  const dataSource = useMemo(() => {
    return listRolesFilters ? listRolesFilters : (withAuth && listRolesByAuth) || listRoles;
  }, [withAuth, listRoles, listRolesByAuth, listRolesFilters]);

  const renderItem = useCallback(
    (role: any, Option: any) => {
      return (
        <Option key={role[valueProp]} value={role[valueProp]}>
          <span>{`${role.roleName}-${role.roleCode}`}</span>
        </Option>
      );
    },
    [valueProp],
  );

  const renderReadElement = useCallback(() => {
    const { value, showMode, linkTo, customShow } = props;
    if (Array.isArray(value)) {
      return value.map((id) => getRoleField({ id }) || id).join('、');
    }
    if (!value) return;
    const name = getRoleField({ id: value });
    const record = getRoleInfo(value);
    if (isEmpty(record)) return value;
    switch (showMode) {
      case 'link':
        return renderlinkEle(value, name, linkTo);
      case 'custom':
        return customShow && customShow(value, record);
      default:
        return name;
    }
  }, [value, showMode, linkTo, customShow]);

  const optionLabel = useMemo(() => {
    if (!value) return;
    const fn = (id: string) => {
      const item = getRoleInfo(id);
      if (isEmpty(item)) return value;
      return `${item.roleName}-${item.roleCode}`;
    };
    if (Array.isArray(value)) {
      return value.map((id) => fn(id)).join('、');
    } else {
      return fn(value);
    }
  }, [value]);

  useEffect(() => {
    fetch();
  }, []);

  return (
    <GridCellEditWrapper autoFocus={restProps.autoFocus} onBlur={onBlur} visible={visible || selectFocus}>
      <BaseSelect
        dataSource={dataSource}
        value={value}
        multiple={multiple}
        selectorId={`RoleSelector:${userId}`}
        valueProp={valueProp}
        labelProp={labelProp}
        isFilter={false}
        optionLabel={optionLabel}
        onSearch={handlerSelectorSearch}
        onChange={handlerSelectorChange}
        renderItem={renderItem}
        onLoupeClick={() => setVisible(true)}
        renderReadElement={renderReadElement}
        onFocus={() => setSelectFocus(true)}
        onBlur={handlerSelectorBlur}
        {...restProps}
      />
      <SelectorModal
        onCancel={() => setVisible(false)}
        multiple={multiple}
        onOk={handlerChange}
        visible={visible}
        valueProp={valueProp}
        withAuth={withAuth}
        value={multiple ? value : value && [value]}
      />
    </GridCellEditWrapper>
  );
};
SelectorFormItem.defaultProps = {
  multiple: false,
  allowClear: true,
  valueProp: 'id',
  labelProp: 'roleName',
  withAuth: false,
};

export default connect(({ selectors, user }: any) => ({
  userId: user.currentUser.id,
  listRoles: selectors.listRoles,
  listRolesByAuth: selectors.listRolesByAuth,
  listRolesFilters: selectors.listRolesFilters,
  listRole4selector: selectors.listRole4selector,
}))(SelectorFormItem);
